import axios from "axios";
import { Dialog } from "vant";
import { API_BASE } from "../config";
import router from "../router";
import { app } from "../store/AppStore";

/**
 * @param response - AxiosResponse data
 */
function isResponseFail(response) {
  const { success, error_code } = response;
  return [
    typeof success === "boolean" && !success,
    typeof error_code === "number"
  ].includes(true);
}

async function reLoginAndTryAgain(url, option) {
  await app.reLogin();
  return request(url, option);
}

function redirectToLogin() {
  router.replace({ name: "Login" });
}

export const request = (url, options = {}) =>
  new Promise((resolve, reject) => {
    const token = app.getToken();

    options.headers = {
      Authorization: "Basic cGhvbmU6cGhvbmVfc2VjcmV0",
      "Cedar-Auth": token && `bearer ${token}`,
      ...options.header
    };

    console.debug(options);

    axios
      .request({
        url,
        baseURL: API_BASE,
        ...options
      })
      .then(({ data: response }) => {
        const { data } = response;

        if (isResponseFail(response)) {
          reject(response);
          return;
        }

        resolve(data || response);
      })
      .catch(async e => {
        console.log(e);

        if (!axios.isAxiosError(e)) {
          reject(e);
          return;
        }

        const { response } = e;

        const isAuthError = response?.status === 401;

        if (isAuthError) {
          if (!app.canReLogin()) {
            redirectToLogin();
            return;
          }

          try {
            resolve(await reLoginAndTryAgain(url, options));
          } catch (e) {
            console.error(e);
            app.cleanTokens();
            redirectToLogin();
          }
          return;
        }

        // Other Errors
        const message =
          response?.data?.msg || response?.statusText || "服务繁忙";

        Dialog.alert({
          message: message
        });

        reject({ ...e, _handler: true });
      });
  });
